package org.codingq92.project.bio_chat.client;

import ch.qos.logback.core.util.StringUtil;
import org.codingq92.project.bio_chat.util.Constants;

import javax.swing.*;
import java.awt.*;

public class ChatFrame extends JFrame {
    private JTextArea chatArea;
    private JTextField messageField;
    private DefaultListModel<String> userListModel;
    private JList<String> chooseList; // 用于获取选中的用户
    private JCheckBox privateChatCheckBox; // 私聊复选框
    public final String username;

    public ChatFrame(String username, java.util.List<String> onlineUsers) {
        super(username);
        this.username = username;
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(800, 600);
        setLocationRelativeTo(null);
        // 主面板，使用BorderLayout布局
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        // 左侧在线用户列表区域
        createUserListPanel(mainPanel, onlineUsers);
        // 右侧聊天内容和输入区域
        createChatPanel(mainPanel);
        getContentPane().add(mainPanel);
        setVisible(true);
        // 模拟系统欢迎消息
        appendMessage("[系统消息]", "欢迎 " + username + " 加入聊天！");
    }

    /**
     * 更新在线用户列表
     *
     * @param newOnlineUsers 新的在线用户数据列表
     */
    public void updateUserList(java.util.List<String> newOnlineUsers) {
        userListModel.clear(); // 清空原有数据
        for (String user : newOnlineUsers) {
            userListModel.addElement(user); // 逐个添加新用户
        }
    }

    /**
     * 发送消息方法，将输入框内容发送到聊天显示区
     */
    private void sendMessage() {
        String message = messageField.getText().trim();
        if (!message.isEmpty()) {
            // 1.如果选中了某人 + 勾选了私聊 就是和此人私聊
            // 2.如果选中了某人 + 没有勾选私聊 就是@此人
            // 3.其余都是群聊
            String selectedValue = chooseList.getSelectedValue();
            boolean selected = privateChatCheckBox.isSelected();
            if (!StringUtil.isNullOrEmpty(selectedValue) && selected) {
                message = username + "(" + Constants.getTime() + "): \n  " + message + "\n";
                System.out.println("选中了 " + selectedValue + "，正在和 " + selectedValue + " 私聊>>> " + message);
                LoginFrame.sendPrivateMsg(selectedValue, message);
            } else if (!StringUtil.isNullOrEmpty(selectedValue) && !selected) {
                message = username + "(" + Constants.getTime() + "): \n  @" + selectedValue + " " + message + "\n";
                System.out.println("选中了 " + selectedValue + "，正在 @ " + selectedValue + ">>> " + message);
                LoginFrame.sendGroupMsg(message);
            } else {
                message = username + "(" + Constants.getTime() + "): \n  " + message + "\n";
                System.out.println("没有选中用户，正在群聊>>> " + message);
                LoginFrame.sendGroupMsg(message);
            }
            messageField.setText("");
        }
    }

    /**
     * 向聊天内容显示区追加消息
     *
     * @param sender  消息发送者标识
     * @param message 消息内容
     */
    public void appendMessage(String sender, String message) {
        if (StringUtil.isNullOrEmpty(sender)) {
            chatArea.append(message);
        } else {
            chatArea.append(sender + " " + message + "\n");
        }
        // 滚动到最新消息位置
        chatArea.setCaretPosition(chatArea.getDocument().getLength());
    }

    /**
     * 创建右侧聊天内容显示和消息输入区域
     *
     * @param mainPanel 主面板，用于添加聊天相关组件
     */
    private void createChatPanel(JPanel mainPanel) {
        JPanel chatMainPanel = new JPanel(new BorderLayout());
        // 聊天内容显示区
        chatArea = new JTextArea();
        chatArea.setEditable(false);
        chatArea.setLineWrap(true);
        chatArea.setWrapStyleWord(true);
        chatArea.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        chatArea.setBorder(BorderFactory.createTitledBorder("聊天内容"));
        JScrollPane chatScrollPane = new JScrollPane(chatArea);
        chatMainPanel.add(chatScrollPane, BorderLayout.CENTER);
        // 底部消息输入和发送区域
        JPanel inputPanel = new JPanel(new BorderLayout());
        inputPanel.setBorder(BorderFactory.createEmptyBorder(5, 0, 0, 30));
        messageField = new JTextField();
        messageField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        // 新建一个面板，用来放发送按钮和私聊复选框，水平排列
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 5, 0));
        JButton sendButton = new JButton("发送");
        sendButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        sendButton.setBackground(new Color(173, 216, 230));
        sendButton.setForeground(Color.BLACK);
        sendButton.setFocusPainted(false);
        sendButton.addActionListener(e -> sendMessage());
        privateChatCheckBox = new JCheckBox("私聊");
        privateChatCheckBox.setSelected(false);
        // 把按钮和复选框加到新建的面板里
        buttonPanel.add(sendButton);
        buttonPanel.add(privateChatCheckBox);
        messageField.addActionListener(e -> sendMessage());
        inputPanel.add(messageField, BorderLayout.CENTER);
        // 把放了按钮和复选框的面板，加到输入区域的东边
        inputPanel.add(buttonPanel, BorderLayout.EAST);
        chatMainPanel.add(inputPanel, BorderLayout.SOUTH);
        mainPanel.add(chatMainPanel, BorderLayout.CENTER);
    }

    /**
     * 创建左侧在线用户列表面板
     *
     * @param mainPanel   主面板，用于添加用户列表面板
     * @param onlineUsers 在线用户数据列表
     */
    private void createUserListPanel(JPanel mainPanel, java.util.List<String> onlineUsers) {
        JPanel userListPanel = new JPanel(new BorderLayout());
        userListPanel.setPreferredSize(new Dimension(180, 0));
        userListPanel.setBorder(BorderFactory.createTitledBorder("在线用户"));
        userListModel = new DefaultListModel<>();
        chooseList = new JList<>(userListModel); // 后续的选中事件 触发@ 和 私聊
        chooseList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        for (String user : onlineUsers) {
            userListModel.addElement(user);
        }
        chooseList.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        chooseList.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        JScrollPane userScrollPane = new JScrollPane(chooseList);
        userListPanel.add(userScrollPane, BorderLayout.CENTER);
        mainPanel.add(userListPanel, BorderLayout.WEST);
    }

}